<?
require_once('includes/config.php');
require_once('includes/functions/func.global.php');
require_once('includes/functions/func.login.php');
require_once('includes/classes/class.template_engine.php');
require_once('includes/lang/lang_'.$config['lang'].'.php');

// Connect to database
db_connect($config);

// Start session
session_start();

// Set number of errors to 0
$errors = 0;

// Set default error message
$login_error = '';

if(isset($_POST['forgot']))
{
	$_GET['forgot'] = $_POST['forgot'];
}
if(isset($_POST['r']))
{
	$_GET['r'] = $_POST['r'];
}
if(isset($_POST['e']))
{
	$_GET['e'] = $_POST['e'];
}
if(isset($_POST['t']))
{
	$_GET['t'] = $_POST['t'];
}

// Check if they are using a forgot password link
if(isset($_GET['forgot']))
{
	$check_forgot = mysql_fetch_row(mysql_query("SELECT user_id,forgot,username FROM ".$config['db']['pre']."users WHERE email='".addslashes($_GET['e'])."' LIMIT 1"));

	if($_GET['forgot'] == $check_forgot[1])
	{
		if($_GET['forgot'] == md5($_GET['t'].'_:_'.$_GET['r'].'_:_'.$_GET['e']))
		{
			// Check that the link hasn't timed out (30 minutes old)
			if($_GET['t'] > (time()-108000))
			{
				$forgot_error = '';
			
				if(isset($_POST['password']))
				{
					if( (strlen($_POST['password']) < 4) OR (strlen($_POST['password']) > 16) )
					{
						$forgot_error = 'Password must be between 4 and 16 characters';
					}
					else
					{
						if($_POST['password'] == $_POST['password2'])
						{
							mysql_query("UPDATE `".$config['db']['pre']."users` SET `forgot` = '' WHERE `user_id` =".addslashes($check_forgot[0])." LIMIT 1 ;");
							mysql_query("UPDATE `".$config['db']['pre']."users` SET `password` = '".addslashes(md5($_POST['password']))."' WHERE `user_id` =".addslashes($check_forgot[0])." LIMIT 1 ;");
							
							$page = new HtmlTemplate ("templates/" . $config['tpl_name'] . "/message.html");
							
							$page->SetParameter ('SUBJECT','Forgot Password');
							$page->SetParameter ('MESSAGE','Your password has been changed, please <a href="login.php">click here</a> to login.');
							
							$page->SetLoop ('CATS', $cats);
							if(isset($_SESSION['duser']['id']))
							{
								$page->SetParameter ('LOGGEDIN', 1);
							}
							else
							{
								$page->SetParameter ('LOGGEDIN', 0);
							}
							$page->SetParameter ('OVERALL_HEADER', create_header($config,$lang,$cats,'Login'));
							$page->SetParameter ('OVERALL_FOOTER', create_footer($config,$lang));
							$page->CreatePageEcho($lang,$config);
							
							exit;
						}
						else
						{
							$forgot_error = 'Passwords do not match';
						}
					}
				}
			
				$page = new HtmlTemplate ("templates/" . $config['tpl_name'] . "/forgot.html");
				$page->SetLoop ('CATS', $cats);
				$page->SetParameter ('FIELD_FORGOT',$_GET['forgot']);
				$page->SetParameter ('FIELD_R',$_GET['r']);
				$page->SetParameter ('FIELD_E',$_GET['e']);
				$page->SetParameter ('FIELD_T',$_GET['t']);
				$page->SetParameter ('USERNAME',$check_forgot[2]);
				$page->SetParameter ('FORGOT_ERROR',$forgot_error);
				if(isset($_SESSION['duser']['id']))
				{
					$page->SetParameter ('LOGGEDIN', 1);
				}
				else
				{
					$page->SetParameter ('LOGGEDIN', 0);
				}
				$page->SetParameter ('OVERALL_HEADER', create_header($config,$lang,$cats,'Login'));
				$page->SetParameter ('OVERALL_FOOTER', create_footer($config,$lang));
				$page->CreatePageEcho($lang,$config);
				exit;
			}
			else
			{
				$login_error = 'Forgot Password code has expired';
			}
		}
		else
		{
			$login_error = 'Invalid Forgot Password code';
		}
	}
	else
	{
		$login_error = 'Invalid Forgot Password code';
	}
	
	// Get site categories
	$cats = get_cats($config);
	
	$page = new HtmlTemplate ("templates/" . $config['tpl_name'] . "/login.html");
	$page->SetLoop ('CATS', $cats);
	$page->SetParameter ('LOGIN_ERROR',$login_error);
	if(isset($_SESSION['duser']['id']))
	{
		$page->SetParameter ('LOGGEDIN', 1);
	}
	else
	{
		$page->SetParameter ('LOGGEDIN', 0);
	}
	$page->SetParameter ('OVERALL_HEADER', create_header($config,$lang,$cats,'Login'));
	$page->SetParameter ('OVERALL_FOOTER', create_footer($config,$lang));
	$page->CreatePageEcho($lang,$config);
	exit;
}

// Check if they are trying to retrieve their email
if(isset($_POST['email']))
{
	// Lookup the email address
	$email_info = mysql_fetch_row(mysql_query("SELECT user_id FROM ".$config['db']['pre']."users WHERE email='".addslashes($_POST['email'])."' LIMIT 1"));

	// Check if the email address exists
	if(isset($email_info[0]))
	{
		// Send the email
		send_forgot_email($_POST['email'],$email_info[0],$config);
		
		// Get site categories
		$cats = get_cats($config);
		
		$page = new HtmlTemplate ("templates/" . $config['tpl_name'] . "/login.html");
		$page->SetLoop ('CATS', $cats);
		$page->SetParameter ('LOGIN_ERROR','');
		if(isset($_SESSION['duser']['id']))
		{
			$page->SetParameter ('LOGGEDIN', 1);
		}
		else
		{
			$page->SetParameter ('LOGGEDIN', 0);
		}
		$page->SetParameter ('OVERALL_HEADER', create_header($config,$lang,$cats,'Login'));
		$page->SetParameter ('OVERALL_FOOTER', create_footer($config,$lang));
		$page->CreatePageEcho($lang,$config);
		exit;
	}
	else
	{
		// Give email does not exist error
		$login_error = 'Email address does not exist';
	}
}

// Check if a user has submitted the form
if(isset($_POST['username']))
{
	if(!isset($_POST['redirect']))
	{
		$_POST['redirect'] = '';
	}

	// Lookup the users table for that user
	$user_info = mysql_fetch_row(mysql_query("SELECT user_id,remember FROM ".$config['db']['pre']."users WHERE username='".addslashes($_POST['username'])."' AND password='".addslashes(md5($_POST['password']))."' LIMIT 1"));

	// The submitted details are valid
	if(isset($user_info[0]))
	{
		if(isset($_POST['remember']))
		{
			$rem = array();
			$rem['uid'] = $user_info[0];
			$rem['username'] = $_POST['username'];
			$rem['rem'] = $user_info[1];
			$rem['tries'] = 0;
		
			setcookie($config['cookie_name'],serialize($rem),time()+$config['cookie_time']);
		}
	
		$_SESSION['duser']['id'] = $user_info[0];
		$_SESSION['duser']['name'] = $_POST['username'];

		if($_POST['redirect'])
		{
			header("Location: ".$config['site_url'].urldecode($_POST['redirect']));
		}
		else
		{
			header("Location: ".$config['site_url']."index.php");
		}
		exit;
	}
	else
	{
		$login_error = 'Username or Password incorrect';
	}
}

if(isset($_POST['redirect']))
{
	$_GET['redirect'] = $_POST['redirect'];
}

// Get category list
$cats = get_cats($config);

$page = new HtmlTemplate ("templates/" . $config['tpl_name'] . "/login.html");
$page->SetLoop ('CATS', $cats);
$page->SetParameter ('OVERALL_HEADER', create_header($config,$lang,$cats,'Login'));
$page->SetParameter ('OVERALL_FOOTER', create_footer($config,$lang));
$page->SetParameter ('LOGIN_ERROR',$login_error);
if(isset($_GET['redirect']))
{
	$page->SetParameter ('REDIRECT',$_GET['redirect']);
}
else
{
	$page->SetParameter ('REDIRECT',$_GET['redirect']);
}
if(isset($_SESSION['duser']['id']))
{
	$page->SetParameter ('LOGGEDIN', 1);
}
else
{
	$page->SetParameter ('LOGGEDIN', 0);
}
$page->CreatePageEcho($lang,$config);
?>